<?php
/*******************************************************************************
 * Copyright 2009-2014 Amazon Services. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 *
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 
 * specific language governing permissions and limitations under the License.
 *******************************************************************************
 * PHP Version 5
 * @category Amazon
 * @package  Marketplace Web Service Orders
 * @version  2011-01-01
 * Library Version: 2014-10-20
 * Generated: Fri Oct 17 15:37:50 GMT 2014
 */

/**
 * List Orders Sample
 */
require_once '../../../config/common_config.php';
require_once PATH_ROOT.'/inc/global.php';
$db = createMysqlDbLink($mysql_config["of"]);
ini_set('date.timezone','Europe/London');

?>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<?
$now=time();
$nexttime=$now+1800;
$missioncount=$db->getValue("select count(*) from `amazonapitime` where `nexttime`<'$now' and `stat`=1");
if($missioncount==0){//无任务则10分钟后刷新
	echo date("Y-m-d h:i:s",$now)." === ".$now;
	echo "<h1>无可执行任务，等待10分钟后自动重试。。</h1>";
	echo "<script>
function refreshPage() 
{ 
window.location.reload(); 
} 

window.setTimeout('refreshPage()',600000);
</script>";
exit;
}
$query=$db->query("select `key` from `amazonapitime` where `nexttime`<'$now' and `stat`=1 limit 1");
$arr=$db->fetchrow($query);
$account=$arr['key'];echo $account;
$plantime=$arr['nexttime'];
require_once($account.'.config.inc.php');


/************************************************************************
 * Instantiate Implementation of MarketplaceWebServiceOrders
 *
 * AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY constants
 * are defined in the .config.inc.php located in the same
 * directory as this sample
 ***********************************************************************/
// More endpoints are listed in the MWS Developer Guide
// North America:
//$serviceUrl = "https://mws.amazonservices.com/Orders/2011-01-01";
// Europe
//$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2011-01-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/Orders/2011-01-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2011-01-01";


 $config = array (
   'ServiceURL' => $serviceUrl,
   'ProxyHost' => null,
   'ProxyPort' => -1,
   'ProxyUsername' => null,
   'ProxyPassword' => null,
   'MaxErrorRetry' => 3,
 );

 $service = new MarketplaceWebServiceOrders_Client(
        AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY,
        APPLICATION_NAME,
        APPLICATION_VERSION,
        $config);
/************************************************************************
 * Uncomment to try out Mock Service that simulates MarketplaceWebServiceOrders
 * responses without calling MarketplaceWebServiceOrders service.
 *
 * Responses are loaded from local XML files. You can tweak XML files to
 * experiment with various outputs during development
 *
 * XML files available under MarketplaceWebServiceOrders/Mock tree
 *
 ***********************************************************************/
 // $service = new MarketplaceWebServiceOrders_Mock();

/************************************************************************
 * Setup request parameters and uncomment invoke to try out
 * sample for List Orders Action
 ***********************************************************************/
 // @TODO: set request. Action can be passed as MarketplaceWebServiceOrders_Model_ListOrders
 $request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest(); 
 $request->setSellerId(MERCHANT_ID); 

 $marketplaceIdList = new MarketplaceWebServiceOrders_Model_MarketplaceIdList();	
 $marketplaceIdList->setId(array('ATVPDKIKX0DER','A1PA6795UKMFR9','A1F83G8C2ARO7P'));
 $orderStatusList = new MarketplaceWebServiceOrders_Model_PaymentMethodList();
 $orderStatusList->setMethod(array('Unshipped','PartiallyShipped'));

$request->setMarketplaceId($marketplaceIdList);
 //$request->setMarketplaceId(MARKETPLACE_ID);  
 //$request->setMWSAuthToken(AWS_SECRET_ACCESS_KEY); 
 $request->setLastUpdatedAfter(date("Y-m-d\Th:i:s\Z",$plantime));
 $request->setOrderStatus($orderStatusList);
 // object or array of parameters
 invokeListOrders($service, $request);
 echo "<script>window.location.href='http://www.haixing001.com/admin/MarketplaceWebServiceOrders/amapi/GetOrderDetail.php?key=".$account."';</script>";
/**
  * Get List Orders Action Sample
  * Gets competitive pricing and related information for a product identified by
  * the MarketplaceId and ASIN.
  *
  * @param MarketplaceWebServiceOrders_Interface $service instance of MarketplaceWebServiceOrders_Interface
  * @param mixed $request MarketplaceWebServiceOrders_Model_ListOrders or array of parameters
  */

  function invokeListOrders(MarketplaceWebServiceOrders_Interface $service, $request)
  {
	  global $db,$account,$now,$nexttime;
      try {
        $response = $service->ListOrders($request);
        $dom = new DOMDocument();
        $dom->loadXML($response->toXML());
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
       // echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
	    $data=$dom->saveXML();
		$xml = simplexml_load_string($data);
		$data1 = json_decode(json_encode($xml),TRUE);
		//print_r($data1);
		if(count($data1['ListOrdersResult']['Orders'])==0) {
			echo "没有发现新订单。。。<br>";
		}else{
		if(is_array($data1['ListOrdersResult']['Orders']['Order'][0])){
			echo "检测到多个订单。。。。<br>";

		foreach($data1['ListOrdersResult']['Orders']['Order'] as $order){
			$type = "2";
			$stat = "1";
			$mpid = $order['MarketplaceId'];
			switch ($mpid){
			case 'ATVPDKIKX0DER':	$comefrom = getcomefrom($mpid);
			case 'A1PA6795UKMFR9':	$comefrom = getcomefrom($mpid);
			case 'A1F83G8C2ARO7P':	$comefrom = getcomefrom($mpid);
			}
			$ordernum  = $order['AmazonOrderId'];
			$detail=json_encode($order);
			$ostat = "1";
			if(($type=="")||($comefrom=="")||($ordernum=="")||($stat==""))
			{
				echo ("<h1>信息不完整，一分钟后重新执行本任务。。</h1>");
				echo "<script>	function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',60000);</script>";
				exit;
			}
			$sql="insert into `amorderlist` (`type`,`stat`,`comefrom`,`ordernum`,`detail`,`ostat`,`key`)values('$type','$stat','$comefrom','$ordernum','$detail','$ostat','$account')";
			$query=$db->query($sql);
			if($query){
				echo $ordernum." added.<br>";
			}else{
				echo $ordernum." didn't be added.<br>";
			}

		}
		}else{
			echo "检测到1个订单。。。。<br>";
			$order = $data1['ListOrdersResult']['Orders']['Order'];print_r($order);
			$type = "2";
			$stat = "1";
			$mpid = $order['MarketplaceId'];
			switch ($mpid){
			case 'ATVPDKIKX0DER':	$comefrom = getcomefrom($mpid);
			case 'A1PA6795UKMFR9':	$comefrom = getcomefrom($mpid);
			case 'A1F83G8C2ARO7P':	$comefrom = getcomefrom($mpid);
			}
			$ordernum  = $order['AmazonOrderId'];
			$detail=json_encode($order);
			$ostat = "1";

			if(($type=="")||($comefrom=="")||($ordernum=="")||($stat==""))
			{
				echo ("<h1>信息不完整，一分钟后重新执行本任务。。</h1>");
				echo "<script>	function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',60000);</script>";
				exit;
			}
			$sql="insert into `amorderlist` (`type`,`stat`,`comefrom`,`ordernum`,`detail`,`ostat`,`key`)values('$type','$stat','$comefrom','$ordernum','$detail','$ostat','$account')";
			$query=$db->query($sql);
			if($query){
				echo $ordernum." added.<br>";
			}else{
				echo $ordernum." didn't be added.<br>";
			}
		}
		}
			mysql_query("update `amazonapitime` set `lasttime`='$now',`nexttime`='$nexttime' where `key` like '".$account."'");
     } catch (MarketplaceWebServiceOrders_Exception $ex) {
        echo("Caught Exception: " . $ex->getMessage() . "\n");
        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
        echo("Error Code: " . $ex->getErrorCode() . "\n");
        echo("Error Type: " . $ex->getErrorType() . "\n");
        echo("Request ID: " . $ex->getRequestId() . "\n");
        echo("XML: " . $ex->getXML() . "\n");
        echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
		echo ("<h1>发现错误，一分钟后重新执行本任务。。</h1>");
		echo "<script>	function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',60000);</script>";
		exit;
     }
 }



 function getcomefrom($mpid){
	 global $account;
	 $mp=array('A2EUQ1WTGCTBG2'=>'CA','ATVPDKIKX0DER'=>'US','A1PA6795UKMFR9'=>'DE','A1RKKUPIHCS9HS'=>'ES','A13V1IB3VIYZZH'=>'FR','A21TJRUUN4KGV'=>'IN','APJ6JRA9NG5V4'=>'IT','A1F83G8C2ARO7P'=>'UK');
	 $acc=substr($account,0,strlen($account)-2).$mp[$mpid];echo $acc." : ";
	 $sql="select * from `come_from` where `cf_name` like '$acc'";
	 $query=mysql_query($sql);
	 if($query){
		 $arr=mysql_fetch_array($query);
		 return $arr['cf_id'];
	 }else{
		 die("Unknown Source!");
	 }
 }
 ?>
 </body>
 </html>